<template>
  <div :class="title === 'add' || title==='check'? 'creative_request_form-body': 'creative_request_form-body-edit'">
    <el-form ref="form" :model="form" label-width="150px" :rules="rules">
      <el-row :gutter="20" v-if="title !== 'edit'">
        <el-col span="12">
          <el-form-item prop="name" label="offer :">
            <el-input
              disabled
              size="mini"
              v-model="offerDetail.name"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20"
              v-if="title !== 'edit && (offerDetail.androidAppUrl != null && offerDetail.androidAppUrl != \'\')'">
        <el-col span="20">
          <el-form-item label="Android :">
            <a :href="offerDetail.androidAppUrl" target="_blank">{{ offerDetail.androidAppUrl }}</a>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-if="title !== 'edit' && (offerDetail.iosAppUrl != null && offerDetail.iosAppUrl != '')">
        <el-col span="20">
          <el-form-item label="IOS :">
            <a :href="offerDetail.iosAppUrl" target="_blank">{{ offerDetail.iosAppUrl }}</a>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20"
              v-if="title !== 'edit' && (offerDetail.websiteAppUrl != null && offerDetail.websiteAppUrl != '')">
        <el-col span="20">
          <el-form-item label="Website :">
            <a :href="offerDetail.websiteAppUrl" target="_blank">{{ offerDetail.websiteAppUrl }}</a>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col span="20">
          <el-form-item nameItemsDesc label="需求名称:" prop="nameItems">
            <el-select
              id="id-offer-componets-creativerequest-conmponents-request-edit-form-nation"
              size="mini"
              clearable
              filterable
              multiple
              v-model="form.nameItems.nation"
              :disabled="title === 'check'"
              placeholder="请选择地区"
              style="width: 15%"
            >
              <el-option
                v-for="item in nationList"
                :key="item.dictValue"
                :value="item.dictValue"
                :label="item.dictValue"
              >
              </el-option>
            </el-select>
            {{ '-' }}
            <el-select
              id="id-offer-componets-creativerequest-conmponents-request-edit-form-language"
              size="mini"
              clearable
              filterable
              multiple
              v-model="form.nameItems.language"
              :disabled="title === 'check'"
              placeholder="请选择投放语言"
              style="width: 15%"
            >
              <el-option
                v-for="item in languageList"
                :key="item.dictValue"
                :value="item.dictValue"
                :label="item.dictValue"
              >
              </el-option>
            </el-select>
            {{ '-' }}
            <el-select
              id="id-offer-componets-creativerequest-conmponents-request-edit-form-type"
              size="mini"
              clearable
              v-model="form.nameItems.type"
              :disabled="title === 'check'"
              placeholder="请选择类型"
              style="width: 15%"
            >
              <el-option
                v-for="item in requestNameType"
                :key="item.dictValue"
                :value="item.dictValue"
                :label="item.dictValue"
              >
              </el-option>
            </el-select>
            {{ '-' }}
            <el-input id="id-offer-componets-creativerequest-conmponents-request-edit-form-desc"
                      placeholder="请输入需求名称描述" :disabled="title === 'check'" v-model="form.nameItems.desc"
                      clearable size="mini" style="width: 30%"></el-input>
          </el-form-item>
        </el-col>
        <el-col span="10">
          <el-form-item prop="creativeType" label="素材类型 :">
            <el-checkbox-group size="mini" v-model="form.creativeType" style="height: 30px;">
              <el-checkbox
                :disabled="title === 'check'"
                v-for="(item, index) in checkedCreativeTypeList"
                :label="item.id"
                :key="item"
              >
                {{ item.name }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col span="10">
          <el-form-item prop="urgency" label="紧急程度 :">
            <el-radio :disabled="title === 'check'" size="mini" v-model="form.urgency" label='1'
            >紧急
            </el-radio>
            <el-radio :disabled="title === 'check'" size="mini" v-model="form.urgency" label='0'
            >一般
            </el-radio>
          </el-form-item>
        </el-col>
        <el-col span="10">
          <el-form-item label="媒体 :" prop="platform">
            <el-select
              id="id-offer-componets-creativerequest-conmponents-request-edit-form-platform"
              :disabled="title === 'check'"
              size="mini"
              multiple
              v-model="form.platform"
              placeholder="请选择"
              style="width: 70%"
              @change="backToUploadPlatform"
            >
              <el-option
                v-for="item in platformsList"
                :key="item.dictKey"
                :value="item.dictKey"
                :label="item.dictValue"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col span="10" v-if="title !== 'edit'">
          <el-form-item label="需求方 :">
            <el-select
              id="id-offer-componets-creativerequest-conmponents-request-edit-form-requester"
              disabled
              size="mini"
              :disabled="title === 'check'  || !userRole.optimize"
              v-model="form.requester"
              filterable
              placeholder="请选择"
              style="width: 70%">
              <el-option
                v-for="(item, index) in requesterList"
                :key="index"
                :value="item.id"
                :label="item.realName"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col span="10" v-if="title !== 'edit'">
          <el-form-item label="设计师负责人 :" prop="designerManager">
            <el-select
              id="id-offer-componets-creativerequest-conmponents-request-edit-form-designerManager"
              :disabled="title === 'check'"
              size="mini"
              v-model="form.designerManager"
              filterable
              placeholder="请选择"
              style="width: 70%"
            >
              <el-option
                v-for="(item, index) in designerManagerList"
                :key="index"
                :value="item.id"
                :label="item.realName"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col span="10" v-if="title !== 'edit'">
          <el-form-item label="状态 :" prop="status">
            <el-select
              id="id-offer-componets-creativerequest-conmponents-request-edit-form-status"
              size="mini"
              v-model="form.status"
              style="width: 70%"
              :disabled="title !== 'edit'"
              placeholder="请选择"
            >
              <el-option
                v-for="item in changeableStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col span="10">
          <el-form-item label="交付日期 :" prop="expectedTime">
            <el-date-picker
              :disabled="title === 'check'"
              size="mini"
              v-model="form.expectedTime"
              type="date"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              placeholder="选择日期时间"
              align="right"
              :picker-options="pickerOptions"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import {
  getOfferDesigner,
  getOfferDesignerManager,
  getOfferOptimizer,
} from "@/api/offer/creativerequest";
import {getSysDictList} from "@/api/system/dict";
import {getDetail} from "@/api/business/offer";
import {getUserId, selectAll} from "@/api/offer/creativerequest";
import {mapGetters} from "vuex";
import {findArray, findObject} from "@/util/util";
import func from "@/util/func";

export default {
  name: "request-form",
  data() {

    /**
     * 验证
     */
      //素材类型
    let checkCreativeType = (rule, value, callback) => {
        if (this.userRole.optimize) {
          if (value.length === 0) {
            return callback(new Error("请选择素材类型"));
          } else {
            callback();
          }
        } else {
          callback();
        }
      };
    //紧急程度
    let checkUrgency = (rule, value, callback) => {
      if (this.userRole.optimize) {
        if (!value) {
          return callback(new Error("请选择紧急程度"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    //设计师负责人
    let checkDesignerManager = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请选择设计师负责人"));
      } else {
        callback();
      }
    };
    //媒体
    let checkPlatform = (rule, value, callback) => {
      if (this.userRole.optimize || this.userRole.admin) {
        if (value === null || value.length === 0) {
          return callback(new Error("请选择媒体"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    // //需求方
    // let checkRequester = (rule, value, callback) => {
    //   if (this.userRole.optimize) {
    //     if (!value) {
    //       return callback(new Error('请选择需求方'))
    //     } else {
    //       callback();
    //     }
    //   } else {
    //     callback();
    //   }
    // }
    //交付日期
    let checkExpectedTime = (rule, value, callback) => {
      if (this.userRole.optimize) {
        if (!value) {
          return callback(new Error("请选择期望时间"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    //状态
    let checkStatus = (rule, value, callback) => {
      if (this.userRole.optimize) {
        if (!value && value !== 0) {
          return callback(new Error("请选择状态"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    };
    let validateNameItems = (rule, value, callback) => {
      if (value.desc == null || value.desc.trim() == '') {
        return callback(new Error('请输入需求名称描述'))
      } else {
        return callback();
      }
    };
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() <= Date.now() - 24 * 60 * 60 * 1000;
        },
      },
      form: {
        id: this.requestid,
        name: '',
        nameItems: {
          nation: [],
          language: [],
          type: '',
          desc: '',
        },
        offerId: this.offerId,
        creativeType: [], //素材类型
        status: "0", //状态
        requester: null, //需求方
        expectedTime: null, //交付日期
        designerManager: null, //设计师负责人
        platform: [], //平台
        urgency: null, //紧急程度
      },
      checkedCreativeTypeList: [
        {id: "0", name: "图片"},
        {id: "1", name: "视频"},
      ],
      offerDetail: {},
      platformsList: [], // 平台列表
      requestNameType: [],
      nationList: [],
      languageList: [],
      designerList: [], //设计师列表
      // optimizerList: [], //优化师列表
      requesterList: [],//需求方，包括优化师和当前用户
      designerManagerList: [],//设计师负责人
      changeableStatusList: [
        {
          label: "待分配",
          value: "0",
        },
        {
          label: "制作中",
          value: "1",
        },
        {
          label: "待确认",
          value: "2",
        },
        {
          label: "已确认",
          value: "3",
        },
        {
          label: "需求待审核",
          value: "4",
        },
        {
          label: "需求被拒绝",
          value: "5",
        },
      ], //状态列表
      rules: {
        nameItems: [{required: true, message: "请输入需求名称", trigger: "blur",}, {
          validator: validateNameItems,
          trigger: 'change'
        }],
        creativeType: [
          {required: true, validator: checkCreativeType, trigger: "change"},
        ],
        urgency: [
          {required: true, validator: checkUrgency, trigger: "change"},
        ],
        platform: [
          {
            required: this.userRole.optimize || this.userRole.admin,
            validator: checkPlatform,
            trigger: "change",
          },
        ],
        status: [{required: true, validator: checkStatus, trigger: "change"}],
        designerManager: [{required: true, validator: checkDesignerManager, trigger: "change"}],
        expectedTime: [
          {required: true, validator: checkExpectedTime, trigger: "change"},
        ],

      },
    };
  },
  props: {
    tips: String,
    requestid: String,
    offerId: String,
    getPlatform: Function,
    title: String,
    subTitle: String,
    userRole: Object,
    creativeRequestData: Object,
    saveCache: Function,
  },
  computed: {
    ...mapGetters(["permission", "userInfo"]),
  },
  watch: {
    form: {
      deep: true,
      handler(val, old) {
        if (this.saveCache) {
          this.saveCache();
        }
      }
    },
  },
  created() {
    this.init();
    if (this.creativeRequestData != null) {
      this.form.creativeType = func.toList(this.creativeRequestData.creativeRequest.creativeType)
      this.form.platform = func.toList(this.creativeRequestData.creativeRequest.platform)
      this.form.urgency = this.creativeRequestData.creativeRequest.urgency.toString()
      this.form.requester = this.creativeRequestData.creativeRequest.requester
      this.form.designerManager = func.optimizeValue(this.creativeRequestData.creativeRequest.designerManager, -1, '')
      this.form.status = this.creativeRequestData.creativeRequest.status.toString()
      this.form.expectedTime = this.creativeRequestData.creativeRequest.expectedTime
      this.form.name = this.creativeRequestData.creativeRequest.name
      this.form.nameItems = this.parseRequestName(this.form.name);
    }
  },
  methods: {
    //初始化
    init() {
      let self = this;
      //设计师
      getOfferDesigner(this.offerId).then((res) => {
        this.designerList = res.data.data;
      });
      getOfferDesignerManager(this.offerId).then((res) => {
        this.designerManagerList = res.data.data;
      });
      //优化师
      getOfferOptimizer(this.offerId).then((res) => {
        let requesterList = res.data.data;
        let userIdx = findArray(this.requesterList, this.userInfo.user_id, 'id');
        if (userIdx == -1) {
          requesterList.push({id: this.userInfo.user_id, realName: this.userInfo.real_name})
        }
        this.requesterList = requesterList;
      });

      //设计师
      // getOfferDesignerManager(this.offerId).then((res) => {
      //   this.designerList = res.data.data;
      // });
      //优化师
      // getOfferOptimizer(this.offerId).then((res) => {
      //   this.optimizerList = res.data.data;
      // });
      //媒体
      getSysDictList("platforms,language,request_name_type,nation").then((map) => {
        this.languageList = map['language'];
        this.requestNameType = map['request_name_type'];
        this.nationList = map['nation'];
        this.platformsList = map['platforms'];
        this.form.nameItems = this.parseRequestName(this.form.name);
      });
      getDetail(this.offerId).then((res) => {
        this.offerDetail = res.data.data;

      });
      if (this.title === 'add') {
        this.form.requester = this.userInfo.user_id;
        if (this.userInfo.detail.tenantVariables['ENABLE_REQUEST_DETAIL_AUDIT'] == 'true') {
          this.form.status == 4;
        } else {
          this.form.status == 0;
        }
      }
      if (this.title === 'edit') {

      }
    },
    backToUploadPlatform(val) {
      this.getPlatform(val);
    },
    /**
     * 表单验证
     */
    validateForm() {
      let flag = false;
      this.form.name = this.toRequestName(this.form.nameItems);
      this.$refs.form.validate((valid) => {
        if (valid) {
          flag = true;
        } else {
          flag = false;
        }
      });
      return flag;
    },
    parseRequestName(name) {
      let result = {
        nation: [],
        language: [],
        type: '',
        desc: name,
      };
      if (name == null || this.nationList.length == 0 || this.languageList.length == 0 || this.requestNameType.length == 0) {
        return result;
      } else {
        let divStart = 0;
        let divEnd = name.indexOf('-', divStart);
        if (divEnd != -1) {
          let item = name.substring(divStart, divEnd);
          let itemList = (item != '') ? item.split('&') : [];
          if (itemList.length > 0 && findObject(this.nationList, itemList[0], 'dictValue') != null) {
            name = name.substring(divEnd + 1);
            result.nation = itemList;
            result.desc = name;
          }
        }
        divStart = 0;
        divEnd = name.indexOf('-', divStart);
        if (divEnd != -1) {
          let item = name.substring(divStart, divEnd);
          let itemList = (item != '') ? item.split('&') : [];
          if (itemList.length > 0 && findObject(this.languageList, itemList[0], 'dictValue') != null) {
            name = name.substring(divEnd + 1);
            result.language = itemList;
            result.desc = name;
          }
        }
        divStart = 0;
        divEnd = name.indexOf('-', divStart);
        if (divEnd != -1) {
          let item = name.substring(divStart, divEnd);
          if (findObject(this.requestNameType, item, 'dictValue') != null) {
            name = name.substring(divEnd + 1);
            result.type = item;
            result.desc = name;
          }
        }
        return result;
      }
    },
    toRequestName(nameItems) {
      if (nameItems == null) {
        return '';
      } else {
        let nameItemList = [];
        if (nameItems.nation != null && nameItems.nation.length > 0) {
          nameItemList.push(nameItems.nation.join('&'));
        }
        if (nameItems.language != null && nameItems.language.length > 0) {
          nameItemList.push(nameItems.language.join('&'));
        }
        if (nameItems.type != null && nameItems.type != '') {
          nameItemList.push(nameItems.type);
        }
        if (nameItems.desc != null && nameItems.desc != '') {
          nameItemList.push(nameItems.desc.trim());
        }
        return nameItemList.join('-');
      }
    },
  },
};
</script>

<style scoped lang="scss">
.creative_request_form-body {
  width: 80%;
  margin: 0 auto;
  -webkit-box-shadow: 2px 2px 19px 2px rgba(0, 0, 0, 0.18);
  box-shadow: 2px 2px 19px 2px rgba(0, 0, 0, 0.18);
  border-radius: 20px;
  padding: 15px;
}

.creative_request_form-body-edit {
  width: 100%;
  margin: 0 auto;
  -webkit-box-shadow: 2px 2px 19px 2px rgba(0, 0, 0, 0.18);
  box-shadow: 2px 2px 19px 2px rgba(0, 0, 0, 0.18);
  border-radius: 20px;
  padding: 15px;
}

/deep/ [nameItemsDesc] .el-form-item__error {
  margin-left: 48% !important;
}
</style>
